<template>
  <div class="category">
    <nav-bar class="top-bar">
      <span slot="center">商品分类</span>
    </nav-bar>
    <div class="scroll-content">
      <tab-menu :categories="categories" @selectItem="changeIndex"/>
      <tab-content-category :subcategories="showSubcategory"/>
    </div>
  </div>
</template>

<script>
  import {getCategory,getSubcategory,getCategoryDetail} from 'network/category'
  import NavBar from "components/common/navbar/NavBar";
  import TabMenu from "./childCompos/TabMenu";
  import TabContentCategory from "./childCompos/TabContentCategory";

  export default {
    name: "Categrory",
    components:{
      NavBar,
      TabMenu,
      TabContentCategory
    },
    data(){
      return{
        categories:[],
        categoryData:{},
        currentIndex:-1
      }
    },
    created() {
      this._getCategory()
    },
    computed:{
      showSubcategory() {
        if (this.currentIndex === -1) return {}
        return this.categoryData[this.currentIndex].subcategories
      }
    },
    methods:{
      changeIndex(index){
        this._getSubcategories(index)
      },
      _getCategory(){
        getCategory().then(res => {
          this.categories = res.data.category.list

          for(let i = 0; i < this.categories.length; i++){
            this.categoryData[i] = {
              subcategories: {},
              categoryDetail: {
                pop:[],
                new:[],
                sell:[]
              }
            }
          }
          this._getSubcategories(0)
        })
      },
      _getSubcategories(index){
        this.currentIndex = index;
        const mailkey = this.categories[index].maitKey;
        getSubcategory(mailkey).then(res => {
          this.categoryData[index].subcategories = res.data
          this.categoryData = {...this.categoryData}
          this._getCategoryDetail('pop')
          this._getCategoryDetail('new')
          this._getCategoryDetail('sell')
        })
      },
      _getCategoryDetail(type){
        const miniWallkey = this.categories[this.currentIndex].miniWallkey;
        getCategoryDetail(miniWallkey, type).then(res => {
          this.categoryData[this.currentIndex].categoryDetail[type] = res
          this.categoryData = {...this.categoryData}
        })
      }
    }
  }
</script>

<style scoped>
  .scroll-content{
    width: 100%;
    display: flex;
  }
  .category{
    width: 100%;
  }
  .top-bar{
    background-color: var(--color-tint);
    font-weight: 700;
    color: #fff;
  }
</style>